package com.example.joke.base.dialog;

import android.content.Context;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import java.lang.ref.WeakReference;

// dialog view的辅助处理类
class DialogViewHelper {

    private View mContentView = null;

    // 使用软引用，是为了防止霸气侧漏
    private SparseArray<WeakReference<View>> mViews;
    public DialogViewHelper(Context context, int mViewLayoutResId) {
        this();
        mContentView = LayoutInflater.from(context).inflate(mViewLayoutResId, null);
    }

    public DialogViewHelper() {
        mViews = new SparseArray<>();
    }

    // 设置布局
    public void setContentView(View contentView) {
        this.mContentView = contentView;
    }

    // 设置文本
    public void setText(int viewId, CharSequence text) {
        // 优化：减少findviewbyid次数，通过缓存，SparseArray
        TextView tv = getView(viewId);
        if (tv != null) {
            tv.setText(text);
        }
    }

    public  <T extends View> T getView(int viewId) {
        // 这种会造成空指针异常，因为初次的时候或者viewid不对时，获取不到，get(key)就会null
//        View view = mViews.get(viewId).get();
        WeakReference<View> viewWeakReference = mViews.get(viewId);
        View view = null;
        if (viewWeakReference != null) {
            view = viewWeakReference.get();
        }
        if (view == null) {
          view = mContentView.findViewById(viewId);
          if (view != null) {   // 有可能传的id不对
            mViews.put(viewId, new WeakReference<>(view));
          }
        }
        return (T) view;
    }

    // 设置点击事件
    public void setOnClickListener(int viewId, View.OnClickListener listener) {
        // 优化：减少findviewbyid次数，通过缓存，SparseArray
//        View view = mContentView.findViewById(viewId);
        View view = getView(viewId);
        if (view != null) {
            view.setOnClickListener(listener);
        }

    }

    // 获取ContentView
    public View getContentView() {
        return mContentView;
    }
}
